// packageA/pages/cleanWorkHandle/cleanWorkHandle.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');
import Base64 from '../../../utils/Base64.js';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //当前用户
    user: null,
    //传参
    paramObj:null,
    //传参来的id
    id:null,
    //修改信息回显
    editInfo:{},
    //提交按钮禁用
    disabled:false,
    cleanOrderMessageReceive:[]
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      user: app.globalData.userInfo
    })

    if(options.paramObj){
      let paramObj=JSON.parse(options.paramObj);
      console.log('保洁工单传参');
      console.log(paramObj);

      this.setData({
        paramObj: paramObj
      })

      if(paramObj.id){
        this.setData({
          id: paramObj.id
        })
        //获取修改数据
        this.getInfo();
        this.findClearOrderMessageReceive(paramObj.projectId)
        
      }
    }
  },

  findClearOrderMessageReceive(projectId){
		let dataObj={
			selectFields: ['id','name','cleanLeader','cleanOrderUsers'],
      id:projectId
		}
		let param = {
      className: 'depart',
      data: dataObj
		}

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
        let result=res.data.data.result;
        console.log('保洁工单接收人');
        console.log(result); 
        if (result!=null && result.length>0){
          if (result[0].cleanLeader != null){
            this.setData({
              cleanOrderMessageReceive:result[0].cleanOrderUsers
            })
          }
        }
      }
    }).catch((error) => {
     
    })
  },
  
  //提交表单
  confirmForm(e){
    //避免表单重复提交-先禁用按钮
    this.setData({
      disabled:true
    })

    let obj=e.detail.value;
    let td=this.data;
    let editInfo=td.editInfo; 

    let handleResult=obj.handleResult.trim();
    if(!this.formNotEmpty(handleResult,'handleResultMessage','请输入处理详情及结果')){
      return;
    }

    if(!editInfo.completionPic){
      Toast.fail('请上传处理图片');
      return;
    }   

    let param={
      className:'cleanKeepingOrder',
      data:{
        id: td.id,
        //处理详情及结果
        handleResult: handleResult,
        //图
				completionPic: editInfo.completionPic,
				//实际完成时间
				completionTime: util.timeFormat(new Date()),
				//状态变为待验收
				state: 4
      }
    }

    console.log(param.data);
    console.log(this.data.paramObj);
    // if (this.data.paramObj.submitter!=null){
    //   let sendParam={
    //     //接收人user表id（工单创建人）
    //     userId: [this.data.paramObj.submitter],
    //     file: 'cleaningWorkOrderState',
    //     //跳转
    //     jump: true,
    //     data:{
    //       //项目名
    //       thing31: this.data.paramObj.projectName,
    //       //接单人
    //       phrase14: this.data.paramObj.handlerName,
    //       //工单标题（投诉问题）
    //       //thing33: this.data.receiveOrderObj.problem+"(处理人:"+param.data.handler.name+")",
    //       thing33: this.data.paramObj.problem,
    //       //工单状态（投诉地点）
    //       phrase15: '已处理',
    //       //通知时间
    //       time10: util.timeFormat(new Date())
    //     }
    //   } 

    //   console.log(sendParam);
    //   CommonService.sendMessage(sendParam).then(res=>{
    //   }).catch((error) => {
    //   })
    // }

    // return


    //避免表单重复提交
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '数据提交中...'
    });

    CommonService.goSave(param).then(res=>{
      this.setData({
        disabled:false
      })
      if (res.statusCode == 200 && res.data.success == true){
        Toast.success('成功');

        if (this.data.cleanOrderMessageReceive!=null && this.data.cleanOrderMessageReceive.length>0){
          // 使用 map 方法提取 id 并生成新数组
          const idArray = this.data.cleanOrderMessageReceive.map(item => item.id);
          let sendParam={
            //接收人user表id（工单创建人）
            userId: idArray,
            file: 'cleaningWorkOrderState',
            //跳转
            jump: true,
            data:{
              //项目名
              thing31: this.data.paramObj.projectName,
              //接单人
              phrase14: this.data.paramObj.handlerName,
              //工单标题（投诉问题）
              //thing33: this.data.receiveOrderObj.problem+"(处理人:"+param.data.handler.name+")",
              thing33: this.data.paramObj.problem,
              //工单状态（投诉地点）
              phrase15: '待验收',
              //通知时间
              time10: util.timeFormat(new Date())
            }
          } 
    
          console.log(sendParam);
          CommonService.sendMessage(sendParam).then(res=>{
          }).catch((error) => {
          })
        }


        setTimeout(() => {
          //返回列表页并刷新数据
          this.backAndRefresh();
        }, 1000);
      }else if(res.statusCode==202){
        Toast.fail('您操作太快了,请勿重复提交');
      }else{
        Toast.fail('操作失败');
      }
    }).catch((error) => {
      Toast.fail('操作失败');
    })  
  },

  //获取修改数据
  getInfo(){
    let param = {
      isAuth: false,
      className: 'cleanKeepingOrder',
      data: {
        id: this.data.id,
				selectFields: ['id','project','place','problem','remark','submitter','submissionTime','handler','handlingTime','handleResult','completionPic','planCompletionTime'],
				nbl: Base64.encode(util.timeFormatDay(new Date()))
      }
    }

    CommonService.goFindList(param).then(res => {
      if(res.data.data && res.data.data.result && res.data.data.result.length) {
				let result=res.data.data.result[0];
				
        //创建时间
        if(result.submissionTime){
          result.self_submissionTime=util.timeFormat(result.submissionTime);
				}
				
				//接单时间
        if(result.handlingTime){
          result.self_handlingTime=util.timeFormat(result.handlingTime);
				}

				//预计完成时间
        if(result.planCompletionTime){
          result.self_planCompletionTime=util.timeFormat(result.planCompletionTime);
				}

        console.log('工单详情');
        console.log(result);
       
        this.setData({
          editInfo: result
        })
      }
    }).catch((error) => {
    })
  },

  //非空验证（field要先去掉空格）
  formNotEmpty(field,messageField,messageCon){
    if(!field){
      let obj = {};
      obj[messageField] = messageCon;
      obj['disabled'] = true;
      this.setData(obj);
      return false;
    }else{
      return true;
    }
  },

  //用户输入时清除错误提示
  clearMessage(e) {
    let field = e.target.dataset.message;
    let obj = {};
    obj[field] = "";
    obj['disabled'] = false;
    this.setData(obj);
  },  

  //获取图片上传组件的传值
  getUploadUrl(data){
    let imgUrls=data.detail;
    if(imgUrls.length){
      let pic='editInfo.completionPic';
      this.setData({
        [pic]: imgUrls
      })
    }else{
			this.setData({
        [pic]: null
      })
		}

		this.setData({
			disabled: false
		})
  },

  //预览图片
  onPreviewImage(e) {
    let detail = e.target.dataset.detail;
    let src = e.target.dataset.src;

    wx.previewImage({
      current: src,
      urls: detail
    })
  },

  //返回列表页并刷新数据
  backAndRefresh(){
    let pages = getCurrentPages();
    let prevPage = pages[pages.length - 2];

    prevPage.refreshListAndPage();
    wx.navigateBack();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})